package com.houger.license;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LicenseInterceptor implements HandlerInterceptor {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    private static final String[] EXCLUDE_PATHS = {
        "/api/activate**",
        "/api/fingerprint**",
        "/swagger**",     // 示例：同时排除Swagger
        "/v3/api-docs**",   // 示例：排除OpenAPI文档
        "/error"
    };

    private LicenseService licenseService;

    @Autowired
    public void setContextManager(LicenseService licenseService) {
        this.licenseService = licenseService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String path = request.getRequestURI();

        // 检查排除路径
        for (String pattern : EXCLUDE_PATHS) {
            if (PATH_MATCHER.match(pattern, path)) {
                return true;
            }
        }

        // 授权验证逻辑
        if (!licenseService.checkLicense()) {
            throw new LicenseException("软件未激活或已过期");
        }
        return true;
    }
}